<?php

namespace forfun\service;

use forfun\context\CoreContext;
use forfun\controller\vo\AgreeForm;
use forfun\repository\AgreeRecordRepository;
use forfun\repository\CoupletReplyRepository;
use forfun\repository\entity\AgreeRecord;

class AgreeRecordService {
    /**
     * 点赞.
     * @param AgreeForm $agreeForm
     * @return void
     */
    public static function addAgree($agreeForm) {
        $agreeRecordRepository = new AgreeRecordRepository();
        $agreeRecordRepository->pUpdateDB()->startTran();
        $agreeRecordRepository->deleteByUserIdAndTypeAndRecordId(CoreContext::getUser()->getId(), $agreeForm->getType(), $agreeForm->getRecordId());
        $agreeRecordRepository->addFavour(CoreContext::getUser()->getId(), $agreeForm->getType(), $agreeForm->getRecordId());
        if ($agreeForm->getType() == AgreeRecord::TYPE_COUPLET_REPLY) {
            $coupletReplyRepository = new CoupletReplyRepository();
            $coupletReplyRepository->update(array(
                'agree_number' => array('agree_number=agree_number+1')
            ), array(
                'id' => $agreeForm->getRecordId()
            ));
        }
        $agreeRecordRepository->pUpdateDB()->commitTran();
    }

    /**
     * 取消点赞.
     * @param $agreeForm
     * @return void
     */
    public static function deleteAgree($agreeForm) {
        $agreeRecordRepository = new AgreeRecordRepository();
        $agreeRecordRepository->pUpdateDB()->startTran();
        $agreeRecordRepository->deleteByUserIdAndTypeAndRecordId(CoreContext::getUser()->getId(), $agreeForm->getType(), $agreeForm->getRecordId());
        if ($agreeForm->getType() == AgreeRecord::TYPE_COUPLET_REPLY) {
            $coupletReplyRepository = new CoupletReplyRepository();
            $coupletReplyRepository->update(array(
                'agree_number' => array('agree_number=agree_number-1')
            ), array(
                'id' => $agreeForm->getRecordId()
            ));
        }
        $agreeRecordRepository->pUpdateDB()->commitTran();
    }
}